package com.tinelion.flyer.service;


import com.tinelion.flyer.dao.UserDao;
import com.tinelion.flyer.entity.UserEntity;
import com.tinelion.flyer.tools.Md5Util;
import com.tinelion.flyer.tools.TimeUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service
@Slf4j
public class UserService {
    @Autowired
    UserDao userDao;

    public String login(String userName, String password) {
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(userName, password);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(usernamePasswordToken);   //完成登录
            subject.checkRole("用户");
            subject.checkPermission("1");
            return "1";
        } catch (Exception e) {
            log.info("权限不足");
            return "login.html";//返回登录页面
        }
    }
    public UserEntity getUser(String userName) {
        UserEntity userEntity = userDao.getUser(userName);
        if (userEntity != null) {
            return userEntity;
        }
        return null;
    }

    public int add(String email,String userName, String password,String role) {
        if(email==null||userName==null||password==null){
            return 0;
        }
        UserEntity userEntity = userDao.getUser(userName);
        if (userEntity != null) {
            return 0;
        }
       //加盐：
        int salt=(int)(Math.random()*999999999);
        String newpass=Md5Util.md5(password+salt);
        log.info("md5Hash:{}",newpass);
        int result=userDao.add(email,userName, newpass,String.valueOf(salt), TimeUtil.gettime());
        int resultrole=userDao.addrole(userDao.getUser(userName).getId(),role,1);
        if(result==1&&resultrole==1){
            return 1;
        }
        return 0;
    }

}
